/**
 * Created by hubo on 2016/4/18.
 */
var table;
$(function() {
    $("#expression.chosen-select").chosen();

    // 表格
    table = $('#dataList').dataTable({
        "fnServerData" : function(sSource, aoData, fnCallback) {
          var matcher = getMatcher();
            var data = {"start":aoData.start};
            if(!jQuery.isEmptyObject(matcher)){
                data.matcher=JSON.stringify(matcher);
            }
            data.orderBy=JSON.stringify({createTime:-1});
            $.ajax({
                "dataType" : 'json',
                "type" : "POST",
                "url" : ctx + "/service/query",
                "data" :data,
                "success" : function(resp){
                    var obj=resp;
                    obj.iTotalRecords=resp.count;
                    obj.iTotalDisplayRecords=resp.count
                    fnCallback(obj);
                }
            });
        },

        "aoColumnDefs": [
            {
                sDefaultContent: '',
                aTargets: [ '_all' ],
            }
        ],
        sAjaxDataProp:'result',

        "aoColumns" : [ null, {
            "data" : "method"
        }, {
            "data" : "memo"
        }, {
            "data" : "name"
        }, {
            "data" : "author"
        },{
            "data" : "url"
        }, {
            "data" : "state"
        }, null],
        "fnRowCallback" : function(nRow, aData, iDisplayIndex) {
            $('td:eq(0)', nRow).html(iDisplayIndex+1);
            if(aData.state == 'N') {
                $('td:eq(6)', nRow).html('停用');
            }else{
                $('td:eq(6)', nRow).html('启用');
            }
            $('td:eq(7)', nRow).html(getUrl(aData));
        },
        "iDisplayLength": 20,//每页显示20条数据
        "bLengthChange":false/*每页长度禁止选择*/
    });

});
/**
 * 获取查询条件
 * @returns {{}}
 */
function  getMatcher(){
    var method = document.getElementById("queryMethod").value;
    var name = document.getElementById("queryMethodName").value;
    var author = document.getElementById("queryAuthor").value;

    var matcher={};
    if(method!=""){
        matcher.method=method.trim();
    }
    if(name!=""){
        matcher.name=name.trim();
    }
    if(author!=""){
        matcher.author=author.trim();
    }
    return matcher;
}

/**
 * 搜索
 */
$('#serach').click(function() {
    table.fnDraw();
});
/**
 * 导出excel的弹出框
 */
$('#exceldownload').click(function() {
    $("#exceldownloadmoadl").modal('show');
    $("#auditState.chosen-select").chosen();
});
/**
 * 以excel进行数据导出
 * @param data
 * @returns {string}
 */
$("#excel-data").click(function(){
    var data={};
     var matcher = getMatcher();

     if(!jQuery.isEmptyObject(matcher)){
         data.matcher=JSON.stringify(matcher);
     }
     data.columns = getColumns();
     data.columnTxt = getColumnTxt();
     console.log(data.columns);debugger;
     data.orderBy=JSON.stringify({createTime:-1});
     $("#excel").attr('action', ctx + "/service/export?data="+JSON.stringify(data)).submit();
    /*清空选中字段*/
    $('#auditState').val("").trigger('chosen:updated');
});
$("#excel_close").click(function(){
    /*清空选中字段*/
    $('#auditState').val("").trigger('chosen:updated');
});
function getColumnTxt(){
    var sortedArr =  $(".search-choice-close").sort(function(src,target){
        return $(src).attr("data-option-array-index")-$(target).attr("data-option-array-index");
    });

    var columnTxts = $(sortedArr).map(function(i,item){
        return $(item).parent().children("span").text();
    }).get().join();
    if(columnTxts == ""){
       var columns = [];
        $("#auditState option").each(function(){  //遍历所有option
            var column = $(this).text();   //获取option值
            columns.push(column);
        })
        columnTxts = columns.join();
    }
    return columnTxts;
}
function getColumns(){
    var columns = $("#auditState").val();
    if(columns != null){
        return columns.join();
    }
    columns = [];
    $("#auditState option").each(function(){  //遍历所有option
        var column = $(this).val();   //获取option值
        columns.push(column);
    })
    return columns.join();
}
function getUrl(data) {
    var str = '';
    str += '<a href="javascript:void(0)" onclick="update(\''+data.method+'\')" class="pRight"><i class="fa text-navy ">编辑</i></a>&nbsp;&nbsp;';
    str += '<a href="#" onclick="delete_(\'' + data.method +'\')" class="pRight"><i class="fa text-navy">删除</i></a>&nbsp;&nbsp;';
    if(data.state=="N"){
        str += '<a href="#" onclick="open_(\'' + data.method +'\')" class="pRight"><i class="fa text-navy">开启</i></a>&nbsp;&nbsp;';
    }else if(data.state=="Y"){
        str += '<a href="#" onclick="close_(\'' + data.method +'\')" class="pRight"><i class="fa text-navy">关闭</i></a>&nbsp;&nbsp;';
    }

    return str;
}

function open_(method){
    $.ajax({
        url:ctx+"/service/open",
        type:'post',
        data:{
            "method":method
        },
        dataType:'json',
        timeout:ajaxTimeout,
        error:function(json){
            toastr.error("开启失败")
        },
        success:function(json){
            //重新渲染table
            if(json.returnCode=='T'){
                toastr.success(json.returnMsg)
            }else{
                toastr.error(json.returnMsg)
            }
            table.fnPageChange(getPageNum(table,false));
        }
    });

}
function close_(method){
    $.ajax({
        url:ctx+"/service/stop",
        type:'post',
        data:{
            "method":method
        },
        dataType:'json',
        timeout:ajaxTimeout,
        error:function(json){
            toastr.error("关闭失败")
        },
        success:function(json){
            //重新渲染table
            if(json.returnCode=='T'){
                toastr.success(json.returnMsg)
            }else{
                toastr.error(json.returnMsg)
            }
            table.fnPageChange(getPageNum(table,false));
        }
    });
}


function delete_(method){
    var confirmStr = "确认删除此接口信息吗？";
    if(!window.confirm(confirmStr)) {
        return;
    }
    $.ajax({
        url:ctx+"/service/delete",
        type:'post',
        data:{
            "method":method
        },
        dataType:'json',
        timeout:ajaxTimeout,
        error:function(json){
            toastr.error("删除失败")
        },
        success:function(json){
            if(json.returnCode=='T'){
                toastr.success(json.returnMsg)
            }else{
                toastr.error(json.returnMsg)
            }
            table.fnPageChange(getPageNum(table,false));

        }
    });
}

// 编辑
function update(method) {
	$("#method").val(method);
	$("#commonForm").attr('action', ctx + "/service/updateUI").submit();
}



/**
 * 根据table对象返回跳转页码
 * @param dataTable jquery.dataTable对象
 * @param isDelete 是否为删除？删除需要考虑最后一页只有一条数据的情况
 * @returns
 */
function getPageNum(dataTable,isDelete){
    var currentPageLength = table.fnGetNodes().length;//获取当前数据的条数
    var tableSetings=dataTable.fnSettings();
    var paging_length=tableSetings._iDisplayLength;//当前每页显示多少
    var page_start=tableSetings._iDisplayStart;//当前页开始
    var page=Div(page_start,paging_length,currentPageLength,isDelete);
    return page;
};